'use client'

import { useEffect, useState, useCallback, useMemo } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import api from '@/lib/api'
import { toast } from 'react-hot-toast'
import { Button } from '@/components/ui/button'
import RequireAuth from '@/components/auth/RequireAuth'
import CountdownTimer from '@/components/orders/CountdownTimer'
import ReviewDialog from '@/components/orders/ReviewDialog'

interface Order {
  id: number
  spot_id: number
  quantity: number
  total_price: number
  status: string
  visit_date: string
  created_at: string
  contact_name: string
  contact_phone: string
  spot: {
    name: string
    images: string
    price: number
  }
  rating?: number
  comment?: string
  commented_at?: string
  is_anonymous?: boolean
}

export default function OrderDetailPage() {
  const params = useParams()
  const router = useRouter()
  const [order, setOrder] = useState<Order | null>(null)
  const [loading, setLoading] = useState(true)
  const [showReview, setShowReview] = useState(false)

  const fetchOrder = useCallback(async () => {
    try {
      setLoading(true)
      if (!params.id) {
        toast.error('订单ID不存在')
        return
      }
      const res = await api.get(`/api/orders/${params.id}`)
      console.log('订单详情数据:', res.data)
      setOrder(res.data)
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '获取订单详情失败')
    } finally {
      setLoading(false)
    }
  }, [params.id])

  // 使用 useMemo 缓存 onTimeout 回调
  const handleTimeout = async () => {
    try {
      await api.post(`/api/orders/${params.id}/cancel`)
      fetchOrder()  // 刷新订单状态
    } catch (error) {
      console.error('Failed to cancel timed out order:', error)
    }
  }

  useEffect(() => {
    fetchOrder()
  }, [fetchOrder])

  const handlePay = async () => {
    try {
      await api.post(`/api/orders/${params.id}/pay`)
      toast.success('支付成功')
      fetchOrder() // 刷新订单状态
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '支付失败')
    }
  }

  const handleCancel = async () => {
    try {
      await api.post(`/api/orders/${params.id}/cancel`)
      toast.success('订单已取消')
      fetchOrder() // 刷新订单状态
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '取消订单失败')
    }
  }

  const handleDelete = async () => {
    if (!confirm('确定要删除此订单吗？')) {
      return
    }
    
    try {
      await api.delete(`/api/orders/${params.id}`)
      toast.success('订单已删除')
      router.push('/orders')  // 删除成功后跳转到订单列表
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '删除订单失败')
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '待支付'
      case 'paid':
        return '已支付'
      case 'completed':
        return '已完成'
      case 'cancelled':
        return '已取消'
      default:
        return status
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'bg-yellow-100 text-yellow-800'
      case 'paid':
        return 'bg-green-100 text-green-800'
      case 'completed':
        return 'bg-blue-100 text-blue-800'
      case 'cancelled':
        return 'bg-gray-100 text-gray-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  if (loading) {
    return <div>加载中...</div>
  }

  if (!order) {
    return <div>订单不存在</div>
  }

  return (
    <RequireAuth>
      <div className="bg-white">
        <div className="mx-auto max-w-3xl px-4 py-16 sm:px-6 sm:py-24 lg:px-8">
          <div className="max-w-xl">
            <h1 className="text-base font-medium text-indigo-600">订单详情</h1>
            <p className="mt-2 text-4xl font-bold tracking-tight sm:text-5xl">
              {order.spot.name}
            </p>
          </div>

          <div className="mt-10 border-t border-gray-200">
            <dl className="divide-y divide-gray-200">
              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">订单状态</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${getStatusColor(order.status)}`}>
                    {getStatusText(order.status)}
                  </span>
                </dd>
              </div>

              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">门票数量</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  {order.quantity} 张
                </dd>
              </div>

              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">总价</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  ¥{order.total_price}
                </dd>
              </div>

              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">游玩日期</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  {format(new Date(order.visit_date), 'yyyy年MM月dd日', { locale: zhCN })}
                </dd>
              </div>

              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">联系人</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  {order.contact_name}
                </dd>
              </div>

              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">联系电话</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  {order.contact_phone}
                </dd>
              </div>

              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">下单时间</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  {format(new Date(order.created_at), 'yyyy年MM月dd日 HH:mm:ss', { locale: zhCN })}
                </dd>
              </div>

              <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                <dt className="text-sm font-medium text-gray-900">支付状态</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                  {order.status === 'pending' && (
                    <CountdownTimer 
                      createdAt={order.created_at}
                      expiresAt={order.expires_at}
                      orderId={order.id}
                      onTimeout={handleTimeout}
                    />
                  )}
                  {order.status === 'paid' && (
                    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${getStatusColor(order.status)}`}>
                      {getStatusText(order.status)}
                    </span>
                  )}
                </dd>
              </div>

              {order.rating && (
                <div className="py-6 sm:grid sm:grid-cols-3 sm:gap-4">
                  <dt className="text-sm font-medium text-gray-900">评价信息</dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
                    <div className="space-y-2">
                      <div className="flex items-center">
                        {[1, 2, 3, 4, 5].map((value) => (
                          <svg
                            key={value}
                            className={`h-5 w-5 ${
                              value <= order.rating ? 'text-yellow-400' : 'text-gray-200'
                            }`}
                            fill="currentColor"
                            viewBox="0 0 20 20"
                          >
                            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                          </svg>
                        ))}
                      </div>
                      <p className="text-gray-700">{order.comment}</p>
                      <div className="flex justify-between items-center text-sm text-gray-500">
                        <span>
                          {order.is_anonymous ? '匿名评价' : '实名评价'}
                        </span>
                        <span>
                          {format(new Date(order.commented_at), 'yyyy年MM月dd日 HH:mm:ss', { locale: zhCN })}
                        </span>
                      </div>
                    </div>
                  </dd>
                </div>
              )}
            </dl>
          </div>

          {order.status === 'pending' && (
            <div className="mt-10 flex justify-end space-x-4">
              <Button
                variant="outline"
                onClick={handleCancel}
              >
                取消订单
              </Button>
              <Button
                onClick={handlePay}
              >
                立即支付
              </Button>
            </div>
          )}

          {(order.status === 'cancelled' || order.status === 'paid') && (
            <div className="mt-10 flex justify-end space-x-4">
              <Button
                variant="destructive"
                onClick={handleDelete}
              >
                删除订单
              </Button>
              {order.status === 'paid' && (
                <Button onClick={() => setShowReview(true)}>
                  {order.rating ? '修改评价' : '评价订单'}
                </Button>
              )}
            </div>
          )}
        </div>
      </div>

      <ReviewDialog
        orderId={order.id}
        open={showReview}
        onOpenChange={setShowReview}
        onSuccess={fetchOrder}
        initialRating={order.rating}
        initialComment={order.comment}
        initialIsAnonymous={order.is_anonymous}
      />
    </RequireAuth>
  )
} 